package com.myna.csv.utils;

import com.myna.csv.domain.Config;
import lombok.Getter;
import lombok.Setter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Setter
@Getter
public class PropertyUtil {

    private static Map<String, Config> configs = null;

    static {
        configs = getConfigs(PropertyUtil.class.getClassLoader().getResourceAsStream("config.xml"));
    }

    public static Config getConf(String key) {
        return configs.get(key);
    }

    public static String getValue(String key) {
        return configs.get(key).getValue();
    }

    private static Map<String, Config> getConfigs(InputStream inputStream) {
        SAXReader saxReader = new SAXReader();
        Document read = null;
        try {
            read = saxReader.read(inputStream);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String xmlPath = "//PropConf";
        List<Element> list = read.selectNodes(xmlPath);
        Map<String, Config> map = null;
        if (list != null) {
            map = new HashMap<>();
            for (Element e : list) {
                Config config = new Config();
                String name = e.elementTextTrim("name");
                String value = e.element("value").getTextTrim();
                String desc = e.elementTextTrim("desc");
                config.setName(name);
                config.setValue(value);
                config.setDesc(desc);
                map.put(config.getName(), config);
            }
        }
        return map;
    }
}
